<?php
namespace Home\Controller;
use Think\Controller;

class LoginController extends Controller {

    public function _initialize() {
        $name = M('theme')->where( array('is_default'=>1) )->getField('name');
        $this->theme(C('NOW_THEME'));
        $this->assign('theme', C('NOW_THEME'));
    }

    //登录页面

    public function index()
    {
        if (IS_AJAX)
        {
            $where["mobile"] = trim(I('post.phone'));
            $where["invitation_code"] = "*";
            $where["shop_id"] = trim(I('post.url_shop_id'));
            $agent = M('agent')->where($where)->find();

            if(!$agent){
                $this->ajaxReturn(array("status" => "error" ,"msg" => "未找到该用户"));
            }
            if($agent["u_status"] != 1){
                $this->ajaxReturn(array("status" => "error" ,"msg" => "用户已被关闭"));
            }
            $agentInfo = M('agent_info')->where( array('agent_id' => $agent['agent_id']) )->find();
            if(!$agentInfo){
                $this->ajaxReturn(array("status" => "error" ,"msg" => "用户尚未注册"));
            }
            $password = md5(md5( trim(I('post.password')) ) .$agentInfo['salt']);
            if($agentInfo["password"] != $password){
                $this->ajaxReturn(array("status" => "error" ,"msg" => "密码错误"));
            }

            session('reception_shopid', $agent['shop_id']);
            session('user_id', $agentInfo['agent_id']);
            session('aavatar', $agentInfo['avatar']);
            session('auser_name', $agent['agent_name']);
            session('amobile', $agent['mobile']);
            session('is_agent',$agent['is_agent']);
//            session('url_shop_id', trim(I('post.url_shop_id')));
            $this->ajaxReturn(array("status" => "success"));
        } else {

            $login_user_id = session("user_id");
            $url_shop_id = trim(I('get.shop_id'));

            $shop = M('shop')->where( array('id'=>$url_shop_id,'state'=>1) )->find();
            if (empty($shop)) {
                $this->error('不存在此店铺');
            } else {
                session('url_shop_id', $url_shop_id);
            }

            $shop_id = M('agent')->where(array('agent_id'=>$login_user_id))->getField("shop_id");
            if($shop_id == $url_shop_id){
                $this->redirect('Setting/personal');
            }
            $this->assign('url_shop_id', trim(I('get.shop_id')));
            $this->site_title = "登录";
            $this->display();
        }
    }
    // 退出
    public function logout()
    {
        session('user_id', null);
        session('arank_id',null);
        session('aavatar', null);
        session('auser_name', null);
        session('amobile', null);
        session('arank_name', null);
        session('is_agent',null);
        session('reception_shopid', null);
        $this->ajaxReturn(1);
    }
}